package org.graduation.recruitment.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * Jackson配置类，用于自定义ObjectMapper的配置。
 */
@Configuration
public class JacksonConfig {

    /**
     * 创建并配置ObjectMapper的Bean实例。
     * 如果容器中不存在ObjectMapper的Bean，则该方法会被调用以创建一个新的ObjectMapper实例。
     *
     * @param builder Jackson2ObjectMapperBuilder，用于构建ObjectMapper实例。
     * @return 配置好的ObjectMapper实例。
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        // 构建ObjectMapper，禁用XML映射
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // 自定义空值序列化行为
        SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
        serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                // 当序列化空值时，输出空字符串
                jsonGenerator.writeString("");
            }
        });

        return objectMapper;
    }

}
